﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace gk.Games.SudokuSolver
{
    public class SudokuCellCollection:IValueChecker
    {
        public List<SudokuCell> Cells { get; private set; }

        #region IValueChecker Members

        public SudokuCellCollection()
        {
            Cells = new List<SudokuCell>(9);
            //InitCells(Cells);
        }

        private void InitCells(List<SudokuCell> cells)
        {
            for (int i = 0; i < 9; i++)
            {
                SudokuCell cell = new SudokuCell();
                cells.Add(cell);
            }
        }

        public bool CanAddValue(int newValue)
        {
            foreach (var cell in Cells)
            {
                if (cell.Value.HasValue && cell.Value == newValue) return false;
                if (!cell.Value.HasValue) continue;                
            }
            return true;
        }

        public void AddCell(SudokuCell cell)
        {
            cell.OnValueSet += new EventHandler(cell_OnValueSet);
            Cells.Add(cell);
        }



        void cell_OnValueSet(object sender, EventArgs e)
        {
            ProcessCells();
        }



        public void ProcessCells()
        {
            List<int> gatheredValues = new List<int>();
            foreach (var cell in Cells)
            {
                if (!cell.Value.HasValue) continue;
                gatheredValues.Add(cell.Value.Value);
            }

            foreach (var cell in Cells)
            {
                if (cell.Value.HasValue) continue;
                foreach (int g in gatheredValues)
                {
                    cell.PossibleValues.Remove(g);
                }
            }
        }

        #endregion
    }
}
